﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Mozlite.Components
{
    /// <summary>
    /// 后台服务管理类。
    /// </summary>
    public static class Tasks
    {
        static Tasks()
        {
            tasks = Cores.FindType<TaskBase>().ToDictionary<TaskBase, string>(task => task.TaskName.ToLower());
        }

        private static readonly Dictionary<string, TaskBase> tasks;
        private static readonly object locker = new object();
        /// <summary>
        /// 注册后台服务。
        /// </summary>
        public static void Register()
        {
            var thread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    lock (locker)
                    {
                        foreach (var task in tasks.Values)
                        {
                            if (!task.CanExecute())
                                continue;
                            var taskThread = new Thread(new ParameterizedThreadStart(obj =>
                            {
                                try
                                {
                                    var to = obj as TaskBase;
                                    to.Execute();
                                    to.LastExecuteTime = DateTime.Now;
                                }
                                catch { }
                            }));
                            taskThread.IsBackground = true;
                            taskThread.Start(task);
                        }
                    }
                    Thread.Sleep(60 * 1000);
                }
            }));
            thread.IsBackground = true;
            thread.Start();
        }
    }
}
